package class

import (
	"ginweb/common"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"strings"
	"time"
)

type Class struct {
	Id        int    `gorm:"column:id;primary_key" json:"id"`
	ClassName string `json:"class_name"`
	StartDate int64  `json:"start_date"`
	EndDate   int64  `json:"end_date"`
	DateRange string `sql:"-"`

	Teacher       string `json:"teacher"`
	StudentNumber int    `json:"student_number"`
	CreateTime    int64  `json:"create_time"`
}

var TeacherList = map[int]string{1: "wang xiao chun", 2: "wan ji"}

func (Class) TableName() string {
	return "class_list"
}

func getTeacher(ids string) string {

	str := ""

	teacherSlice := strings.Split(ids, ",")

	for _, v := range teacherSlice {
		key, _ := strconv.Atoi(v)
		str += TeacherList[key] + ", "
	}

	return str

}

func List(c *gin.Context) {

	if !common.CheckLogin(c) {
		c.Redirect(302, "/login")
	}

	db := common.InitDB()
	defer db.Close()

	var list []Class
	db.Order("id desc").Find(&list)

	for k, v := range list {
		list[k].Teacher = getTeacher(v.Teacher)
		list[k].DateRange = time.Unix(v.StartDate, 0).Format("2006-01-02") + " / " + time.Unix(v.EndDate, 0).Format("2006-01-02")

		//list[k].StartDate = v.StartDate.
	}

	c.HTML(http.StatusOK, "class_list.html", gin.H{
		"title": "Main website",
		"list":  list,
		"nav":   "/class/list",
	})

}

func Add(c *gin.Context) {

	if !common.CheckLogin(c) {
		c.Redirect(302, "/login")
	}

	c.HTML(http.StatusOK, "class_add.html", gin.H{
		"title":        "Main website",
		"teacher_list": TeacherList,
	})
}

func Insert(c *gin.Context) {

	class := Class{}
	c.ShouldBind(&class)

	if class.ClassName == "" || class.Teacher == "" {
		common.ReturnMsg(200, 0, "参数错误", c)
		return
	}

	db := common.InitDB()
	defer db.Close()

	var info []Class

	db.Where("class_name=?", class.ClassName).First(&info)

	if len(info) > 0 {
		common.ReturnMsg(200, 0, "班级己存在", c)
		return
	}

	class.CreateTime = time.Now().Unix()
	err := db.Create(&class).Error
	if err != nil {
		common.ReturnMsg(200, 0, "保存班级失败", c)
		return
	}

	common.ReturnMsg(200, 1, "保存成功", c)

}
